//
//  LTFNewsView.m
//  NeteaseNews
//
//  Created by liutaifeng on 16/4/13.
//  Copyright © 2016年 liutaifeng. All rights reserved.
//

#import "LTFNewsHeadLineView.h"
#import "AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "LTFHeadLineModel.h"
#import "LTFFirstTableViewCell.h"
#import "LTFSecondTableViewCell.h"
#import "LTFThirdTableViewCell.h"
#import "LTFCollectionViewCell.h"
#import "LTFCollectionViewModel.h"
#import "MJRefresh.h"
#define WIDTH self.frame.size.width
#define HEIGHT self.frame.size.height
@interface LTFNewsHeadLineView ()
<
 UITableViewDataSource,
 UITableViewDelegate,
 UICollectionViewDataSource,
 UICollectionViewDelegate
>
//头视图
@property (nonatomic, retain) UIView *headHeadLineView;

@property (nonatomic, retain) UITableView *headLineTableView;//tableView
@property (nonatomic, retain) NSMutableArray *headLineArray;//数组
//轮播图
@property (nonatomic, retain) UICollectionView *collectionView;
//轮播图数组
@property (nonatomic, retain) NSMutableArray *collectionViewArray;
//图片位置
@property (nonatomic, retain) UIPageControl *page;//页数
//定时
@property (nonatomic, retain) NSTimer *myTimer;

@property (nonatomic,assign) NSInteger pages;

@property (nonatomic, retain) NSString *docPath;
@end

@implementation LTFNewsHeadLineView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];
        [self setUpData];
    }
    return  self;
}

- (void)setUpData {
    _headLineTableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(upData)];
    _headLineTableView.mj_footer = [MJRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(moreData)];
}
- (void)upData {
    self.pages = 0;
    [self createData];
}
- (void)moreData {
    [self createData];
}

//- (void)create {
//    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES) lastObject];
//    self.docPath = [sandBox stringByAppendingPathComponent:@"T1348647909107.plist"];
//    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:_docPath];
//    if (<#condition#>) {
//        <#statements#>
//    }
//}

- (void)createView {
    self.collectionViewArray = [NSMutableArray array];
    self.headLineArray = [NSMutableArray array];
    self.headLineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    self.headLineTableView.backgroundColor = [UIColor whiteColor];
    self.headLineTableView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.headLineTableView];
    //设置代理
    self.headLineTableView.delegate = self;
    self.headLineTableView.dataSource = self;
    self.headLineTableView.tag = 1006;
    //头视图
    self.headHeadLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
    self.headHeadLineView.backgroundColor = [UIColor redColor];
    [self addSubview:self.headHeadLineView];
    
    
    
    
    //轮播图底部
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH, HEIGHT / 3);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //轮播图
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3) collectionViewLayout:layout];
    [self.headHeadLineView addSubview:self.collectionView];
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[LTFCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([LTFCollectionViewCell class])];
    self.headLineTableView.tableHeaderView = self.headHeadLineView;
    
    
    self.myTimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(collectionViewClick) userInfo:nil repeats:YES];
    
    
    //图片位置
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH / 3 * 2 + 35, self.collectionView.frame.size.height / 6 * 5, 90, 20)];
    [self.headHeadLineView addSubview:self.page];
    //总数量
    self.page.numberOfPages = 4;
    
   // _page.currentPage = 0;
}


//循环播放
- (void)collectionViewClick {
    [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x + WIDTH, 0) animated:YES];
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.collectionView.contentOffset.x == 5 * WIDTH) {
        self.collectionView.contentOffset = CGPointMake(WIDTH, 0);
    }
    if (self.collectionView.contentOffset.x == 0) {
        self.collectionView.contentOffset = CGPointMake(4 * WIDTH, 0);
    }
    self.page.currentPage = self.collectionView.contentOffset.x / WIDTH - 1;
}

//collectionView的第一个协议
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collectionViewArray.count;
}
//collectionView的第二个协议
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LTFCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LTFCollectionViewCell class]) forIndexPath:indexPath];
    LTFCollectionViewModel *model = self.collectionViewArray[indexPath.row];
    [cell.picImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhenwei.png"]];
    cell.titleLabel.text = model.title;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LTFCollectionViewModel *model = self.collectionViewArray[indexPath.row];
    NSString *str = [model.url substringFromIndex:4];
    NSString *string =  [str stringByReplacingOccurrencesOfString:@"|" withString:@"/"];
    [self.delegate sendHeadAddress:string];
}


//tableView的第一个必须协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.headLineArray.count;
}
//tableView的第二个必须协议
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFHeadLineModel *model = self.headLineArray[indexPath.row];
    if (model.imgnewextra == nil) {
        if (model.imgType == 0) {
            static NSString *firstReuse = @"firstReuse";
            LTFFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:firstReuse];
            if (!cell) {
                cell = [[[LTFFirstTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:firstReuse] autorelease];
            }
            //图片
            [cell.picImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
            //标题
            cell.titleLabel.text = model.title;
            //内容
            cell.contentLabel.text = model.digest;
            //跟帖
            if (model.TAGS != nil) {
                cell.countLabel.text = model.TAGS;
                cell.countLabel.textColor = [UIColor blueColor];
                
                cell.countLabel.layer.borderWidth = 1;
                cell.countLabel.layer.borderColor = [UIColor blueColor].CGColor;
                cell.countLabel.font = [UIFont systemFontOfSize:13];
                cell.countLabel.textAlignment = 1;
            } else {
                cell.countLabel.textColor = [UIColor grayColor];
                cell.countLabel.layer.borderWidth = 0;
                cell.countLabel.layer.borderColor = [UIColor clearColor].CGColor;
                cell.countLabel.text = [NSString stringWithFormat:@"%d跟帖", [model.replyCount intValue]];
            }
            return cell;
        }
        else {
            static NSString *secondReuse = @"secondReuse";
            LTFSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:secondReuse];
            if (!cell) {
                cell = [[[LTFSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:secondReuse] autorelease];
            }
            //图片
            [cell.picImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
            //标题
            cell.titleLabel.text = model.title;
            //内容
            cell.contentLabel.text = model.digest;
            //跟帖数
            if (model.TAGS != nil) {
                cell.countLabel.text = model.TAGS;
                cell.countLabel.textColor = [UIColor blueColor];
                cell.countLabel.layer.borderWidth = 1;
                cell.countLabel.layer.borderColor = [UIColor blueColor].CGColor;
                cell.countLabel.font = [UIFont systemFontOfSize:8];
                cell.countLabel.textAlignment = 1;
            } else {
                cell.countLabel.textColor = [UIColor grayColor];
                cell.countLabel.layer.borderWidth = 0;
                cell.countLabel.layer.borderColor = [UIColor clearColor].CGColor;
                cell.countLabel.text = [NSString stringWithFormat:@"%d跟帖", [model.replyCount intValue]];
            }
            
            return cell;
        }
    }
    else {
        static NSString *thirdReuse = @"thirdReuse";
        LTFThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:thirdReuse];
        if (!cell) {
            cell = [[[LTFThirdTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:thirdReuse] autorelease];
        }
        cell.titleLabel.text = model.title;
        if (model.TAGS != nil) {
            cell.countLabel.text = model.TAGS;
            cell.countLabel.textColor = [UIColor blueColor];
            
            cell.countLabel.layer.borderWidth = 1;
            cell.countLabel.layer.borderColor = [UIColor blueColor].CGColor;
            cell.countLabel.font = [UIFont systemFontOfSize:13];
            cell.countLabel.textAlignment = 1;
        } else {
            cell.countLabel.textColor = [UIColor grayColor];
            cell.countLabel.layer.borderWidth = 0;
            cell.countLabel.layer.borderColor = [UIColor clearColor].CGColor;
            cell.countLabel.text = [NSString stringWithFormat:@"%d跟帖", [model.replyCount intValue]];
        }
        [cell.firstImageView setImageWithURL:[NSURL URLWithString:model.imgsrc] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        [cell.secondImageView setImageWithURL:[NSURL URLWithString:[model.imgnewextra firstObject][@"imgsrc"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        [cell.thirdImageView setImageWithURL:[NSURL URLWithString:[model.imgnewextra lastObject][@"imgsrc"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        return cell;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFHeadLineModel *model = self.headLineArray[indexPath.row];
    [self.delegate sendAddress:model.docid];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LTFHeadLineModel *model = self.headLineArray[indexPath.row];
    if (model.imgnewextra == nil) {
        if (model.imgType == 0) {
            return 130;
        } else {
            return 280;
        }
    } else {
        return 180;
    }
}
- (void)setString:(NSString *)string {
    if (_string != string) {
        [_string release];
        _string = [string retain];
        [self createData];
    }
}
- (void)createData {
    
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/list/%@/%ld-20.html", self.string, self.pages];
    //请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dictionary = responseObject;
        NSArray *T1348647909107 = dictionary[@"T1348647909107"];
        self.headLineArray = [LTFHeadLineModel BaseModelByArray: T1348647909107];
        if (self.headLineArray.count != 0) {
           [self.headLineArray removeObjectAtIndex:0];
            self.pages += 10;
            [_headLineTableView.mj_header endRefreshing];
            [_headLineTableView.mj_footer endRefreshing];
            [self.headLineTableView reloadData];
            self.headLineTableView.contentOffset = CGPointMake(0, 0);
            NSArray *ads = [T1348647909107 firstObject][@"ads"];
            self.collectionViewArray = [LTFCollectionViewModel BaseModelByArray:ads];
            if (self.collectionViewArray.count == 5) {
                [self.collectionViewArray removeLastObject];
            }
            LTFCollectionViewModel *firstModel = [self.collectionViewArray lastObject];
            LTFCollectionViewModel *lastModel = [self.collectionViewArray firstObject];
            [self.collectionViewArray insertObject:firstModel atIndex:0];
            [self.collectionViewArray addObject:lastModel];
            
            
            
            [self.collectionView reloadData];
            [self.collectionView setContentOffset:CGPointMake(WIDTH, 0)];
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
}

- (void)dealloc
{
    [super dealloc];
}





/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
